from selenium.common.exceptions import NoSuchElementException


class EMailChangeTest(object):

    def test_email_change(self):
        self.go_to_main_page()
        self.change_my_email('admin', 'admin', 'elena@qweqwe.qwe')

    def change_my_email(self,user, password, new_email):
        self.login_as(user, password)
        self.go_to_my_profile(user);
        self.driver.find_element_by_id("email").clear()
        self.driver.find_element_by_id("email").send_keys(new_email)
        self.driver.find_element_by_name("submit").click()
        #self.failIf(self.there_is_error_message(), "Error on page!")
        #assert self.driver.find_element_by_xpath("//*/h2[text()[contains(.,'User management')]]")
        assert (self.driver.find_element_by_class_name("content").find_element_by_tag_name("select") and
                self.driver.find_element_by_xpath("//*/*[@alt='Remove']"))
        self.go_to_my_profile( user)
        assert self.driver.find_element_by_xpath("//*[@id='email' and @value='%s']" % new_email)
        self.logout()

    def there_is_error_message(self):
        try:
            self.driver.find_element_by_xpath("//*/*[@class='error']")
        except NoSuchElementException as e:
            return False

    def login_as(self, login, passwd):
        self.driver.find_element_by_link_text("Log in").click()
        userNameField = self.driver.find_element_by_id("username")
        userNameField.clear()
        userNameField.send_keys(login)
        passwordField = self.driver.find_element_by_name("password")
        passwordField.clear()
        passwordField.send_keys(passwd)
        self.waiter.until(lambda drv: drv.find_element_by_name("submit")).click()
        assert self.driver.find_element_by_link_text("Log out")

    def go_to_main_page(self):
        self.driver.get(self.base_url + "/php4dvd/")

    def go_to_my_profile(self, user):
        self.driver.find_element_by_link_text("My profile").click()
        assert self.driver.find_element_by_xpath("//*/h2[text()[contains(.,'Edit %s')]]" % user)

    def logout(self):
        self.waiter.until(lambda drv: drv.find_element_by_link_text("Log out")).click()
#        self.driver.find_element_by_link_text("Log out").click()
        self.waiter.until(lambda drv: drv.switch_to_alert()).accept()
#        self.driver.switch_to_alert().accept()
        #assert self.driver.find_element_by_link_text("Log in")
        self.assert_(self.is_on_login_page(), "Page not found!")

    def is_on_login_page(self):
        return self.driver.find_element_by_link_text("Log in")
